package com.training1.core.modules.service;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.training1.core.common.exception.ExcelException;
import com.training1.core.common.global.signIn.LoginInfoUtil;
import com.training1.core.common.service.CrudService;
import com.training1.core.entity.ChargeEntity;
import com.training1.core.entity.MemberEntity;
import com.training1.core.entity.SystemParamEntity;
import com.training1.core.exception.BusinessException;
import com.training1.core.modules.dao.ChargeDao;
import com.training1.core.modules.dao.MemberDao;
import com.training1.core.modules.dao.SystemSettingsDao;
import com.training1.util.ImportExcel;
import com.training1.util.SequenceNumberUtil;

@Service
@Transactional
public class ChargeService extends CrudService<ChargeDao,ChargeEntity>{
	
	@Resource
	private MemberDao memberDao;
	
	
	
	@Resource
	private SystemSettingsDao systemSettingDao;
	
	@Transactional
	public Map<String, String> charge(String filePath) {
		Workbook wb;
		File source;
		Sheet sheet;
		Map<String,String> result = new HashMap<>();
		Integer count = 0;
		BigDecimal total = new BigDecimal(0.00);
		//税率
		SystemParamEntity systemRate = systemSettingDao.findEntityByKey("ZH_B_SF");
		
		//消费基金占比
		SystemParamEntity expenseFund = systemSettingDao.findEntityByKey("ZH_B_XF");
		
		BigDecimal totalIncome ;
		BigDecimal avaibleCash ;
		BigDecimal cusumeCash;
		BigDecimal tax ;
		try {
			source = new File(filePath);
			wb = ImportExcel.getwb(source);
			sheet = wb.getSheetAt(0);
			int lastRowNum = sheet.getLastRowNum();
				try {
					for(int i=1 ; i <= lastRowNum ; i++){
						Row row = sheet.getRow(i);
						if(row == null)continue;
						//得到单元格的值
						String cellPhone = ImportExcel.getCellValue(row.getCell(0));
						String month = ImportExcel.getCellValue(row.getCell(2));
						BigDecimal cash = new BigDecimal(ImportExcel.getCellValue(row.getCell(3)));
						ChargeEntity charageEntity = new ChargeEntity();
						charageEntity.setOrderNumber(SequenceNumberUtil.generateOrderNumber());
						charageEntity.setCellPhone(cellPhone);
						charageEntity.setRechargeCash(cash);
						charageEntity.setRechargeMonth(month);
						charageEntity.setRechargeChannel(5);
						charageEntity.setRechargeType(1);
						charageEntity.setCreateBy(LoginInfoUtil.getLoginInfo().getLoginName());
						charageEntity.setUpdateBy(LoginInfoUtil.getLoginInfo().getLoginName());
						if(dao.insert(charageEntity)!=1){
							result.put("err", "导入充值失败,手机号"+cellPhone);
							throw new BusinessException(result);
						}
						MemberEntity memberEntity = memberDao.findMemberByCell(cellPhone);
						
						if(BigDecimal.ZERO.compareTo(memberEntity.getTotalIncome()) < 0) {
							//原有总收益金额>0,原有总收益加上奖励金额
							 totalIncome=memberEntity.getTotalIncome().add(cash);
						} else {
							//原有总收益金额为0
							totalIncome=cash;
						}
						//B区
						//更新可提现
						if(BigDecimal.ZERO.compareTo(memberEntity.getAvaibleCash()) < 0) {
							//原有可提现金额>0,原有可提现金额+扣除税率金额+扣除消费基金金额
							//B区原有可提现金额+扣除税率和消费基金
							avaibleCash=memberEntity.getAvaibleCash().add(cash.multiply(
									(BigDecimal.valueOf(1 - Double.valueOf(systemRate.getParamValue())/100))).multiply(
											(BigDecimal.valueOf(1 - Double.valueOf(expenseFund.getParamValue())/100))));
						} else {
							//B区扣除税率和消费基金
							avaibleCash=cash.multiply(
									(BigDecimal.valueOf(1 - Double.valueOf(systemRate.getParamValue())/100))).multiply(
											(BigDecimal.valueOf(1 - Double.valueOf(expenseFund.getParamValue())/100)));
						}
						//更新消费基金
						if(BigDecimal.ZERO.compareTo(memberEntity.getCusumeCash()) < 0) {
							//原有消费基金金额>0,原有消费基金金额+扣除消费基金金额
							//B区原有可提现金额+扣除消费基金
							cusumeCash=memberEntity.getCusumeCash().add(cash.multiply(
									(BigDecimal.valueOf(1 - Double.valueOf(systemRate.getParamValue())/100))).multiply(
											(BigDecimal.valueOf(Double.valueOf(expenseFund.getParamValue())/100))));
						} else {
							//B区扣除消费基金
							cusumeCash=cash.multiply(
									(BigDecimal.valueOf(1 - Double.valueOf(systemRate.getParamValue())/100))).multiply(
											(BigDecimal.valueOf(Double.valueOf(expenseFund.getParamValue())/100)));
						}
						//更新税费
						if(BigDecimal.ZERO.compareTo(memberEntity.getTax() == null ? BigDecimal.ZERO : memberEntity.getTax() ) < 0) {
							//原有税费金额>0,原税费+扣除税费
							//B区原税费+扣除税费
							tax=memberEntity.getTax().add(cash.multiply(BigDecimal.valueOf(Double.valueOf(systemRate.getParamValue())/100)));
						} else {
							//B区扣除税费
							tax=cash.multiply(BigDecimal.valueOf(Double.valueOf(systemRate.getParamValue())/100));
						}
						Map<String,Object> param = new HashMap<>();
						param.put("cellPhone", cellPhone);
						param.put("totalIncome", totalIncome);
						param.put("avaibleCash", avaibleCash);
						param.put("cusumeCash", cusumeCash);
						param.put("tax", tax);
						if(memberDao.updateEarnings(param)!=1){
							result.put("err", "导入充值失败,手机号"+cellPhone);
							throw new BusinessException(result);
						}
						count++;
						total=total.add(cash);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		result.put("success", "充值成功,合计"+count+"笔,共"+total+"元");
		return result;
	}

	@Transactional
	public Map<String, String> upload(MultipartFile file) {
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
		String originalFilename = file.getOriginalFilename();
		Map<String,String> map = null;
		if (file != null && originalFilename != null && originalFilename.length() > 0) {
			// 存储文件的物理路径
			String file_path = "E:\\upload\\";
			// 文件新名称
			String newfileName = new Date().getTime() + originalFilename.substring(originalFilename.lastIndexOf("."));
			// 创建文件
			File newFile = new File(file_path + newfileName);
			// 判断父路径是否存在
			if (!newFile.getParentFile().exists()) {
				// 创建父路径
				newFile.getParentFile().mkdirs();
			}
			try {
				// 创建文件
				file.transferTo(newFile);
				//验证excel表中数据
				map = ImportExcel.validate(in, memberDao, newFile.getAbsolutePath());
				//将文件路径存入map,用于返回给前台，让批量提现获取路径。
				map.put("url", newFile.getAbsolutePath());
			} catch (ExcelException e) {
				e.printStackTrace();
				//存放错误信息
				map = new HashMap<String,String>();
				map.put("result", "err");
				map.put("errMsg", e.getErrMsg().toString().substring(e.getErrMsg().toString().indexOf('[')+1, e.getErrMsg().toString().indexOf(']')));
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		return map;
	}
}